define(function (require, exports, module) {
    var $ = require('jquery');

    var angular = require('angular');

    var util = require("util");

    require('./custom_menu_service');

    var customMenu = angular.module('customMenu',['ngMessages','directives.util','directives.dragsort','customMenu.service']);
    customMenu.config(function ($routeProvider) {
        $routeProvider
            .when('/custom-menu', {
                controller: 'customMenuCtl',
                templateUrl: "business_modules/custom_menu/ngviews/custom_menu.html"
            })
            .otherwise({
                redirectTo: '/index'
            });
    });
    customMenu.controller('customMenuCtl',['$scope','customMenuService', function($scope,customMenuService){
        var ONE_MAX_NUM = 3,TWO_MAX_NUM = 5;
        //回复类型:1文字，2图文，3语音，4图片，5视频，6卡券，7链接，8音乐，9关键字


        function setNameMsg(data,type){
            if(data.level == 0){
                if(type !== 'rename'){
                    var oneMenuNum = $scope.menuList.length;
                    var remainNum = ONE_MAX_NUM - oneMenuNum;
                    data.message = '还能添加个'+remainNum+'一级菜单，请输入名称（4个汉字或8个字母以内）';
                }
                data.maxlength = 8;
                data.maxlengthMsg = '菜单名称名字不多于4个汉字或8个字母';
            }else{
                if(type !== 'rename'){
                    var items = $scope.menuList[data.parentIndex].items || [];
                    var remainNum = TWO_MAX_NUM - items.length;
                    data.message = '还能添加个'+remainNum+'二级菜单，请输入名称（8个汉字或16个字母以内）';
                }
                data.maxlength = 16;
                data.maxlengthMsg = '菜单名称名字不多于8个汉字或16个字母以内';
            }
        }

        customMenuService.scope = $scope;

        customMenuService.getMenuList();

        $scope.alterMenu = {}

        $scope.getMenuData = function(parentIndex,value){
            var ret = {};

            //一级菜单没有parentIndex
            if(parentIndex == null){
                ret.level = 0;
                ret.sort = $scope.menuList.length;
            }else {
                ret.level = 1;
                ret.parentIndex = parentIndex;
                ret.parent_id = $scope.menuList[parentIndex].id;

                var items = $scope.menuList[parentIndex].items;
                ret.sort = items ? items.length : 0;
            }

            if(value){//为空新增,有值修改
                ret.name = value;
            }
            return ret;
        }
        $scope.renameData = function(){
            var data = {
                level : $scope.currMenu.level,
                sort : $scope.currMenu.sort,
                name : $scope.currMenu.name,
                id : $scope.currMenu.id
            }
            if($scope.currMenu.parent_id){
                data.parent_id = $scope.currMenu.parent_id;
            }
            setNameMsg(data,'rename');
            return data;
        }

        $scope.delMenu = function(){
            util.confirm('删除后该菜单下设置的消息将不会被保存',{
                title : '删除确认',
                ok : function(){
                    customMenuService.deleteMenu({id:$scope.currMenu.id});
                    $scope.currMenu = null;
                }
            });
        }


        $scope.checkOneMenu = function(data){
            if($scope.menuList.length >= ONE_MAX_NUM){
                util.notify('最多只能添加三个一级菜单，当前已达设置上限');
                return false;
            }

            setNameMsg(data);
            return true;
        };


        $scope.checkTwoMenu = function(data){
            var items = $scope.menuList[data.parentIndex].items || [];
            if(items.length >= TWO_MAX_NUM){
                util.notify('最多只能添加五个二级菜单，当前已达设置上限');
                return false;
            }
            setNameMsg(data);
            return true;
        }

        /**
         * 改变当前menu对象
         * @param menu
         */
        $scope.changeCurrMenu = function(menu,callbackFlag){

            if(!callbackFlag && $scope.alterMenu){
                if($scope.alterMenu.type == '7' && $scope.alterMenu.content) {//链接
                    if($scope.alterMenu.content){
                        customMenuService.setMenuJumpPage({
                            id: $scope.currMenu.id,
                            pageUrl: $scope.alterMenu.content
                        })
                    }
                }else if($scope.alterMenu.type && $scope.alterMenu.type != '7'){//发送消息
                    $scope.$broadcast('tabData');
                }
            }

            $scope.currMenu = menu;
            $scope.alterMenu = {};
            var currMenuOpt = {};
            if($scope.currMenu.type>1&&$scope.currMenu.type<6){
                currMenuOpt.content = angular.fromJson($scope.currMenu.content);
            }

            var items = menu.items || [];
            if(menu.level==0 && items.length>0){
                currMenuOpt.OneHasTwo = true;//一级菜单并且有二级子菜单
                currMenuOpt.title = '已经为“'+menu.name+'”添加了二级菜单，无法设置其他动作。你还可以添加'+(TWO_MAX_NUM-items.length)+'个二级菜单'
            }else{
                currMenuOpt.OneHasTwo = false;
                currMenuOpt.title = '请选择订阅者点击“'+menu.name+'”菜单后，公众号做出的响应动作';
            }
            $scope.currMenuOpt = currMenuOpt;

        }

        $scope.addMenu = function(data){
            var params = {
                name : data.name,
                level : data.level,
                sort : data.sort
            }
            if(data.parent_id){
                params.parent_id = data.parent_id
            }
            customMenuService.addMenu(params);
        }
        $scope.renameMenu = function(data){
            var params = {
                name : data.name,
                id : data.id
            }
            customMenuService.renameMenu(params);
        }

        $scope.sortingMenu = function(){
            $scope.sorting = true;
        }
        $scope.sortedMenu = function(){
            $scope.sorting = false;
            var params = [];
            $('.drag-menu-one').each(function(index){
                params.push({
                    id : $(this).data('id'),
                    sort : index
                });
                $(this).find('.drag-menu-two').each(function(index){
                    params.push({
                        id : $(this).data('id'),
                        sort : index
                    });
                })
            })
            customMenuService.setMenuSort({ids:params});
        }
        $scope.alter = function(){
            $scope.alterMenu.alter=true;
            $scope.alterMenu.type=$scope.currMenu.type;
            $scope.alterMenu.content=$scope.currMenu.content;
        }

        $scope.triggerSendMessage = function(){
            $scope.alterMenu.alter=true;
            $scope.alterMenu.type='1';
        }

        $scope.resetObj = {
            followType : 'text',
            title: "重设动作会导致当前菜单内容被清空确定重设？",
            text: function (index) {
                return '';
            },
            validate: function (text) {
                return true;
            },
            ok: function () {
                var content = $scope.alterMenu.content;
                if(content){
                    customMenuService.resetAction({id:$scope.currMenu.id});
                }else{
                    $scope.changeCurrMenu($scope.currMenu,true);
                }
            }
        }

        $scope.$on('giveTabData',function(event,data){
            customMenuService.setMenuSendMessage({
                id: $scope.currMenu.id,
                type : data.type,
                content : data.content
            });
        });

        $scope.$on('tabLinkEnd',function(event,data){
            $scope.$broadcast('initTab',$scope.currMenu);
        });

    }]);
});